package dataImport.action.helper;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import dataImport.exception.InstanceAlreadyCreatedException;


public class XMLReader implements Serializable {

	private static final long serialVersionUID = 7353945754450527856L;

	private static XMLReader instance;

	private Document document;

	private XMLReader() {}

	public static void createInstance(final String fileName) throws ParserConfigurationException, SAXException, IOException, InstanceAlreadyCreatedException {
		if (instance == null) {
			instance = new XMLReader();

			final File file = new File(fileName);
			final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
			final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
			instance.setDocument(documentBuilder.parse(file));
			instance.getDocument().getDocumentElement().normalize();
		}
		else {
			throw new InstanceAlreadyCreatedException(XMLReader.class.getName());
		}
	}

	public static void clearInstance() {
		instance = null;
	}

	public static XMLReader getInstance() {
		return instance;
	}

	public Document getDocument() {
		return this.document;
	}

	private void setDocument(final Document document) {
		this.document = document;
	}
}
